# import http
from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.areas.models import Area
from utils.response_code import RETCODE








class AreasView(View):
    def get(self,request):
        """
        省份：select * from tb_areas where parent_id is null;
        市；select * from tb_areas where parent_id=130000
        县；select * from tb_areas where parent_id = 130200
        获取当前县或者市的上一个级别select * from tb_areas where id = 130200
        """
        #1.接收参数  查询参数
        area_id = request.GET.get("area_id")

        #2.判断  参数

        # 传进来的参数 area_id 没有值--省份
        if not area_id:
            #如果有缓存  用缓存  没有缓存的交互
            from django.core.cache import cache
            province_list = cache.get("province_list")
            if not province_list:
                provinces = Area.objects.filter(parent__isnull = True)
                #构建前端 数据格式
                # provinces_list = []
                # for pro in provinces:
                #     data_dict = {
                #         "id":pro.id,
                #         "name":pro.name,
                #
                #     }
                #     provinces_list.append(data_dict)
                province_list = [{"id":pro.id,"name":pro.name} for pro in provinces]
                #存入缓存
                cache.set("province_list",province_list,3600)
            return http.JsonResponse({"code":RETCODE.OK,"errmsg":"OK" ,'province_list': province_list})
        else:
            from django.core.cache import cache
            sub_data = cache.get("sub_data"+area_id)
            if not sub_data:
                #有值--市和县
                # 构建 前端的数据格式
                # subs = Area.objects.filter(parent_id = area_id)
                # parent_model = Area.objects.get(id=area_id)
                #父级的内容
                parent_model = Area.objects.get(id=area_id)
                #根据父级 获取 下面的 市 或者县
                subs = parent_model.subs.all()

                sub_list = [{ "id":sub.id,"name":sub.name} for sub in subs]
                sub_data = {
                    "id":parent_model.id,
                    "subs":sub_list,
                    "name":parent_model.name,
                }
                #存缓存
                cache.set("sub_data"+area_id,sub_data,3600)
                # 3. 返回结果
            return http.JsonResponse({"code":RETCODE.OK,"errmsg":"OK","sub_data":sub_data})









